package cn.com.moziware.laserlampdemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import org.json.JSONObject;

import java.util.TimerTask;

import cn.com.moziware.aboutdevice.IMoziApiListener;
import cn.com.moziware.aboutdevice.IMoziApiService;

public class LaserLampActivity extends AppCompatActivity {
    public static final String TAG = "LaserLampDemo";

    private ViewHolder viewHolder;
    private static final int PERMISSIONS_REQUEST_CODE = 2;
    private static final String[] PERMISSIONS_REQUIRED = new String[]{"cn.com.moziware.permission.LASER_LAMP"};

    public static IMoziApiService getiMoziApiService() {
        return iMoziApiService;
    }

    private static IMoziApiService iMoziApiService;
    private ServiceConnection serviceConnection = new ServiceConnection() {

        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "Mozi API service disconnected.");
            iMoziApiService = null;
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            iMoziApiService = IMoziApiService.Stub.asInterface(service);
            Log.d(TAG, "App service connected.");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_laser_lamp);

        if (!hasPermissions(this)) {
            requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE);
        } else {
            init();
        }

    }

    private void init() {
        bindService();
        viewHolder = new ViewHolder(this);

        isAvailable(new IMoziApiListener.Stub() {
            @Override
            public void callback(int code, String msg, String data) throws RemoteException {
                if (code == 0) {
                    viewHolder.setClickable(true);
                } else {
                    viewHolder.setClickable(false);
                }
            }
        });

        viewHolder.setOnClickListener(v -> {
            switch (v.getId()) {
                case R.id.laser_off_laser_lamp_bt:
                    laserLampOff();
                    isOpen(new IMoziApiListener.Stub() {
                        @Override
                        public void callback(int code, String msg, String data) throws RemoteException {
                            if (code == 0) {
                                try {
                                    JSONObject jsonObject = new JSONObject(data);
                                    if (jsonObject.has("isOpened")) {
                                        boolean isOpened = jsonObject.getBoolean("isOpened");
                                        Toast.makeText(LaserLampActivity.this, "Laser Lamp is open: " + isOpened, Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    break;
                case R.id.laser_on_laser_lamp_bt:
                    laserLampOn();
                    isOpen(new IMoziApiListener.Stub() {
                        @Override
                        public void callback(int code, String msg, String data) throws RemoteException {
                            if (code == 0) {
                                try {
                                    JSONObject jsonObject = new JSONObject(data);
                                    if (jsonObject.has("isOpened")) {
                                        boolean isOpened = jsonObject.getBoolean("isOpened");
                                        Toast.makeText(LaserLampActivity.this, "Laser Lamp is open: " + isOpened, Toast.LENGTH_SHORT).show();
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    break;
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PERMISSIONS_REQUEST_CODE == requestCode && hasPermissions(this)) {
            init();
        } else {
            Toast.makeText(this, "Permission request failed:" + PERMISSIONS_REQUIRED, Toast.LENGTH_SHORT).show();
        }
    }

    public static boolean hasPermissions(Context context) {
        boolean hasPermissions = false;
        for (String permission : PERMISSIONS_REQUIRED) {
            if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
                hasPermissions = true;
            } else {
                hasPermissions = false;
                break;
            }
        }
        return hasPermissions;
    }

    private void bindService() {
        boolean hasService = isAppInstalled(this, "cn.com.moziware.aboutdevice");
        if (hasService) {
            new Thread(new TimerTask() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    intent.setPackage("cn.com.moziware.aboutdevice");
                    intent.setAction("cn.com.moziware.service.action.LASER_LAMP_API");
                    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                }
            }).start();

        } else {
            Log.e(TAG, "not support moziapi.");
        }
    }

    private boolean isAppInstalled(Context context, String pkgName) {
        PackageManager pm = context.getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }


    public void isAvailable(@NonNull IMoziApiListener listener) {
        IMoziApiService iMoziApiService = getiMoziApiService();
        if (iMoziApiService != null) {
            try {
                iMoziApiService.handler("laserLamp.isAvailable", null, listener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void isOpen(@NonNull IMoziApiListener listener) {
        IMoziApiService iMoziApiService = getiMoziApiService();
        if (iMoziApiService != null) {
            try {
                iMoziApiService.handler("laserLamp.isOpen", null, listener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void laserLampOn() {
        IMoziApiService iMoziApiService = getiMoziApiService();
        if (iMoziApiService != null) {
            try {
                iMoziApiService.handler("laserLamp.open", null, null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void laserLampOff() {
        IMoziApiService iMoziApiService = getiMoziApiService();
        if (iMoziApiService != null) {
            try {
                iMoziApiService.handler("laserLamp.close", null, null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //    public void laserLampOn() {
    //        Intent intent = new Intent("cn.com.moziware.intent.action .CONTROL_LASER_LAMP_ON");
    //        sendMessages(intent);
    //    }
    //
    //    public void laserLampOff() {
    //        Intent intent = new Intent("cn.com.moziware.intent.action.CONTROL_LASER_LAMP_OFF");
    //        sendMessages(intent);
    //    }
    //
    //    public void sendMessages(Intent intent) {
    //        //        intent.setPackage("cn.com.moziware.aboutdevice");
    //        sendBroadcast(intent);
    //    }

    private class ViewHolder {
        private Button laserOnLaserLampBt;
        private Button laserOffLaserLampBt;

        public ViewHolder(Activity activity) {
            laserOnLaserLampBt = activity.findViewById(R.id.laser_on_laser_lamp_bt);
            laserOffLaserLampBt = activity.findViewById(R.id.laser_off_laser_lamp_bt);
        }

        private void setOnClickListener(View.OnClickListener onClickListener) {
            laserOnLaserLampBt.setOnClickListener(onClickListener);
            laserOffLaserLampBt.setOnClickListener(onClickListener);
        }

        private void setClickable(boolean isClick) {
            laserOnLaserLampBt.setClickable(isClick);
            laserOffLaserLampBt.setClickable(isClick);
        }
    }
}